package cn.kgc.javaweb.listener;

import cn.kgc.javaweb.entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.HashMap;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/26
 * @Description:  监听session对象中值的改变
 */
@WebListener
public class SessionAttributeListener implements HttpSessionAttributeListener {

    private HashMap<String,HttpSession> map = new HashMap<>();
    // session对象中添加值
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {

        //System.out.println("==============session  attributeAdded===========");

        HttpSession session = event.getSession();
        String key = event.getName();
        Object value = event.getValue();

        //System.out.println("session = " + session);
        //System.out.println("key = " + key);
        //System.out.println("value = " + value);

        if("user".equals(key)){
            User user = (User)value;
            String username = user.getUsername();
            
            if(map.containsKey(username)){
                HttpSession httpSession = map.get(username);
                httpSession.invalidate();
            }
            map.put(username,session);
        }
    }
    // session对象中删除值
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("==============session  attributeRemoved===========");
        String name = event.getName();
        User user = (User) event.getValue();
        if("user".equals(name)){
            String username = user.getUsername();
            map.remove(username);
        }
    }
    //session对象中更改值
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {


    }
}
